/**
 * 应用程序的启动(入口)文件
 */

const express = require('express'),
    app = express(),
    swig = require('swig'),
    mongoose = require('mongoose'),
    bodyParser = require('body-parser'),
    path = require('path'),
    Cookies = require('cookies'),
    User = require('./models/User.js'),
    path = require('path'),
    Content = require('./models/Content')

app.use(bodyParser.urlencoded({
    extended: true
}))

app.use('/public', express.static(path.resolve(__dirname, 'public')))

app.use(function (req, res, next) {
    req.cookies = new Cookies(req, res);

    req.userInfo = {};
    if (req.cookies.get('userInfo')) {
        try {
            req.userInfo = JSON.parse(req.cookies.get('userInfo'))
            User.findById(req.userInfo._id).then((userInfo) => {
                req.userInfo.isAdmin = userInfo.isAdmin;
                next()
            }).catch(() => next());
        } catch (e) {
            next();
        }
    } else
        next()
})



app.engine('html', swig.renderFile)
app.set('views', path.resolve(__dirname, 'views'))
app.set('view engine', 'html')
swig.setDefaults({
    cache: false
});

app.use('/admin', require('./routers/admin'));
app.use('/api', require('./routers/api'));
app.use('/', require('./routers/main'));

mongoose.connect('mongodb://duanjinqiu.cn:27017/blog', err => {
    if (err)
        console.log('数据库连接失败');
    else {
        const server = app.listen(8081, () => console.log(`http://localhost:${server.address().port}`))
    }
});